package com.cw.kafka.starter.consumer;

import java.util.Optional;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.kafka.support.KafkaHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.cw.kafka.starter.constant.KafkaMessageDto;
import com.cw.kafka.starter.service.KafkaRetryService;

import lombok.extern.slf4j.Slf4j;

/**
 *  kafka消费类
 *
 * @author chenw
 * @version 5.0 since 2020-01-13
 */
@Component
@Slf4j
public class KafkaConsumer {
    @Autowired
    private KafkaRetryService kafkaRetryService;

    @KafkaListener(topics = "demo_topic",groupId = "defaultConsumerGroup")
    public void topic_test(ConsumerRecord<?, ?> record, Acknowledgment ack, @Header(KafkaHeaders.RECEIVED_TOPIC) String topic) {

        Optional message = Optional.ofNullable(record.value());
        if (message.isPresent()) {
            KafkaMessageDto msg = JSON.parseObject((String)record.value(),KafkaMessageDto.class);
            log.info("demo_topic 消费了： Topic:" + topic + ",Message:" + msg);
            log.info("pianyiliang:{},fenqu:{}",record.offset(),record.partition());
            ack.acknowledge();
        }
    }
}